package bll

import (
	"context"

	"manager/event"
	"manager/model"
	"manager/model/entity"
	"manager/store"
	"manager/store/postgres"
	"time"
)

type doc struct {
	iDoc store.IDoc
}

var Doc = &doc{
	iDoc: postgres.Doc,
}

func (a *doc) init() func() {
	return func() {}
}

func (a *doc) onEvent(*event.Data) {}

// Create 创建
func (a *doc) Create(ctx context.Context, in *model.DocCreateRequest) error {
	var (
		err error
	)

	// 构建创建现场数据
	c := buildDoc(in)
	_, err = a.iDoc.Create(ctx, c)
	return err
}

// Update 更新
func (a *doc) Update(ctx context.Context, in *model.DocUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)

	updateAt := time.Now().Unix()
	in.UpdatedAt = &updateAt

	if in.Title != nil {
		dict["title"] = in.Title
	}

	if in.Url != nil {
		dict["url"] = in.Url
	}

	if in.Content != nil {
		dict["content"] = in.Content
	}

	if in.DocType != nil {
		dict["doc_type"] = in.DocType
	}

	if in.StoreType != nil {
		dict["store_type"] = in.StoreType
	}

	if in.UpdatedAt != nil {
		dict["updated_at"] = in.UpdatedAt
	}

	// do other update here
	return a.iDoc.Update(ctx, in.Id, dict)
}

// Delete 删除
func (a *doc) Delete(ctx context.Context, in *model.DocDeleteRequest) error {
	return a.iDoc.Delete(ctx, in.Id)
}

// List 列表查询
func (a *doc) List(ctx context.Context, in *model.DocListRequest) (*model.DocListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.Doc
		out   = &model.DocListResponse{}
	)

	if total, list, err = a.iDoc.List(ctx, in); err != nil {
		return nil, err
	}

	out.Total = total
	out.List = model.DocsEntityToDto(list)

	return out, nil
}

// Find 列表查询
func (a *doc) Find(ctx context.Context, in *model.DocInfoRequest) (*model.DocInfo, error) {
	var (
		err  error
		data *entity.Doc
		out  = &model.DocInfo{}
	)

	if data, err = a.iDoc.Find(ctx, in); err != nil {
		return nil, err
	}

	out = model.DocEntityToDto(data)
	return out, nil
}

// buildDoc 构建创建数据现场
func buildDoc(in *model.DocCreateRequest) *entity.Doc {
	// todo: check the entity is required
	return &entity.Doc{

		Title: in.Title,

		Url: in.Url,

		Content: in.Content,

		DocType: in.DocType,

		StoreType: in.StoreType,

		CreatedAt: time.Now().Unix(),

		UpdatedAt: time.Now().Unix(),
	}
}
